package com.example.videotest;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import fi.iki.elonen.NanoHTTPD;

public class NotificationServer extends NanoHTTPD {

    private static final String TAG = "NotificationServer";
    private static final String deviceIp = "192.168.1.232";
    private Context context;

    public NotificationServer(int port, Context context) {
        super(port);
        this.context = context;
    }

    @Override
    public Response serve(IHTTPSession session) {
        Gson gson = new Gson();
        try {
            // 获取请求体数据
            Map<String, String> files = new HashMap<>();
            session.parseBody(files);
            String jsonBody = files.get("postData");

            // 解析JSON
            Result<FileInfo> payload = gson.fromJson(jsonBody, new TypeToken<Result<FileInfo>>() {}.getType());
            FileInfo fileInfo = payload.getData();

            if (fileInfo == null) {
                return newFixedLengthResponse(Response.Status.BAD_REQUEST, "application/json",
                        gson.toJson(Result.error("传入参数为空！")));
            }

            Log.e(TAG, "Received file URL: " + fileInfo.getFileUrl());
            Log.e(TAG, "Received play count: " + fileInfo.getPlayCount());
            Log.e(TAG, "Received target ip: " + fileInfo.getTargetIp());

            if (!fileInfo.getTargetIp().equals(deviceIp)) {
                return newFixedLengthResponse(Response.Status.BAD_REQUEST, "application/json",
                        gson.toJson(Result.error("传入ip参数与设备ip不匹配！")));
            }

            if (fileInfo.getFileUrl().isEmpty()) {
                return newFixedLengthResponse(Response.Status.BAD_REQUEST, "application/json",
                        gson.toJson(Result.error("待播放视频url为空")));
            }

            if (fileInfo.getPlayCount() <= 0) {
                return newFixedLengthResponse(Response.Status.BAD_REQUEST, "application/json",
                        gson.toJson(Result.error("播放次数必须为正整数")));
            }

            // 启动活动并播放视频
            Intent intent = new Intent(context, FileShowActivity.class);
            intent.putExtra("FILE_URL", fileInfo.getFileUrl());
            intent.putExtra("PLAY_COUNT", fileInfo.getPlayCount());
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

            // 返回成功的Result对象
            return newFixedLengthResponse(Response.Status.OK, "application/json",
                    gson.toJson(Result.success("File URL received successfully!")));

        } catch (Exception e) {
            e.printStackTrace();
            // 返回服务器错误的Result对象
            return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, "application/json",
                    gson.toJson(Result.error("Server error")));
        }
    }

    public void startServer() {
        try {
            start();
            Log.d(TAG, "Server started");
        } catch (IOException e) {
            Log.e(TAG, "Failed to start server", e);
        }
    }

    public void stopServer() {
        stop();
        Log.d(TAG, "Server stopped");
    }
}

